using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.IO;

namespace EventAbstractionAPI.RuleEngine
{
	internal class XMLHelper
	{
        /// <summary>
        /// Add a node to an xml document. 
        /// The root of the subdocument is added at the node indicated by the xpath expression.
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="subdocument"></param>
        /// <returns></returns>
        public static XmlDocument AddXML(XmlDocument doc, String xpath, XmlDocument subdocument)
        {
            //TODO(reliability): check that the rule name is unique. if not throw exception
            //TODO(reliability): check to see that the rule set name is correct. if not throw exception
            //TODO(reliability): add error handling for the xpath compile statement. it is possible that it fails.

            XmlDocument newDoc = new XmlDocument();
            newDoc.LoadXml(doc.OuterXml);

            XPathNavigator nav = newDoc.CreateNavigator();

            xpath = "//wf:RuleDefinitions/wf:RuleDefinitions.RuleSets/wf:RuleSet/wf:RuleSet.Rules";
            ///RuleDefinitions/RuleDefinitions.RuleSets/RuleSet/RuleSet.Rules

            XmlNamespaceManager nsmgr = new XmlNamespaceManager(nav.NameTable);
            nsmgr.AddNamespace("wf", "http://schemas.microsoft.com/winfx/2006/xaml/workflow");

            XPathExpression expr = nav.Compile(xpath);
            expr.SetContext(nsmgr);
            XPathNodeIterator iterator = nav.Select(expr);

            iterator.MoveNext();

            //XPathNavigator clone = iterator.Current.Clone();

            //doc.
            //iterator.
            //doc.GetElementById
            iterator.Current.AppendChild(getDocumentReader(subdocument));

            return newDoc;
        }

        internal static XmlTextReader getDocumentReader(XmlDocument doc)
        {
            return new XmlTextReader(new StringReader(doc.OuterXml));
        }
	}
}
